package com.jgit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Tree对象：存储目录结构，包含多个TreeEntry
 */
public class Tree extends GitObject {
    private List<TreeEntry> entries;
    
    public Tree() {
        this.entries = new ArrayList<>();
    }
    
    public Tree(List<TreeEntry> entries) {
        this.entries = entries;
    }
    
    public static Tree fromContent(byte[] content) {
        List<TreeEntry> entries = new ArrayList<>();
        int offset = 0;
        
        while (offset < content.length) {
            TreeEntry entry = TreeEntry.fromBytes(content, offset);
            entries.add(entry);
            
            // 计算下一个条目的偏移量
            int nullIndex = -1;
            for (int i = offset; i < content.length; i++) {
                if (content[i] == 0) {
                    nullIndex = i;
                    break;
                }
            }
            offset = nullIndex + 1 + 20; // null字节 + 20字节哈希
        }
        
        return new Tree(entries);
    }
    
    @Override
    public String getType() {
        return "tree";
    }
    
    @Override
    public byte[] getRawContent() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (TreeEntry entry : entries) {
            baos.write(entry.toBytes());
        }
        return baos.toByteArray();
    }
    
    public void addEntry(TreeEntry entry) {
        entries.add(entry);
    }
    
    public List<TreeEntry> getEntries() {
        return entries;
    }
    
    public TreeEntry findEntry(String name) {
        for (TreeEntry entry : entries) {
            if (entry.getName().equals(name)) {
                return entry;
            }
        }
        return null;
    }
}

